<template>
  <div class="flowpath-container">
    <div>
      <div class="mb20">
        <span class="color_494949 ft12 pr5">{{ translate('关键字') }}：</span>
        <el-input
          v-model="searchInfo"
          class="w164 mr10"
          :placeholder="translate('请输入关键字')"
        />
        <el-button class="settingBtn mr10" type="primary" @click="getList">
          {{ translate('查询') }}
        </el-button>
      </div>
      <div class="add">
        <el-button
          v-if="MenuAuths('add')"
          class="settingBtn"
          type="primary"
          @click="addFn"
          plain
        >
          {{ translate('新增') }}
        </el-button>
        <el-button type="primary" @click="download()" plain>
          {{ translate('下载') }}
        </el-button>
        <el-upload
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          :action="action"
          :before-upload="beforeUpload"
          class="inline-block"
          :headers="headers"
          name="fileInput"
          :on-error="handleError"
          :on-success="handleSuccess"
          :show-file-list="false"
        >
          <el-button type="primary" @click="uploadFn()" plain>
            {{ translate('导入') }}
          </el-button>
        </el-upload>
        <el-button type="primary" @click="exportFn()" plain>
          {{ translate('导出') }}
        </el-button>
      </div>
      <el-table :data="tableData">
        <!-- <el-table-column label="序号" type="index" width="80" /> -->
        <el-table-column
          :label="translate('门店名称')"
          prop="BranchName"
          show-overflow-tooltip
        />
        <el-table-column
          :label="translate('门店编码')"
          prop="BranchNo"
          show-overflow-tooltip
        />
        <el-table-column :label="translate('门店类型')">
          <template #default="{ row }">
            <div>
              {{ row.BranchType === 0 ? translate('直营') : translate('加盟') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="translate('门店状态')">
          <template #default="{ row }">
            <div>
              {{
                row.BranchStatus === 0 ? translate('无效') : translate('正常')
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="translate('门店图标')">
          <template #default="{ row }">
            <div class="img-container">
              <el-image
                fit="contain"
                :initial-index="9"
                :preview-src-list="[row.LogoURL]"
                :preview-teleported="true"
                :src="row.LogoURL + '?=' + timestamp"
                style="width: 60px; height: 60px"
                :z-index="99999"
                :zoom-rate="1.2"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="translate('门店电话')" prop="BranchTel" />
        <el-table-column
          :label="translate('门店地址')"
          prop="BranchAddress"
          show-overflow-tooltip
        />
        <el-table-column
          :label="translate('门店描述')"
          prop="BranchDescription"
          show-overflow-tooltip
        />
        <el-table-column :label="translate('是否启用')">
          <template #default="{ row }">
            <div>
              {{ row.Enabled === 0 ? translate('否') : translate('是') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          :label="translate('有效期')"
          prop="SSValidity"
          show-overflow-tooltip
        />
        <el-table-column :label="translate('操作')" width="250">
          <template #default="{ row }">
            <el-button
              v-if="MenuAuths('edit')"
              plain
              size="small"
              type="primary"
              @click="detailFn(row)"
            >
              {{ translate('编辑') }}
            </el-button>
            <el-button
              v-if="MenuAuths('delete')"
              plain
              size="small"
              type="danger"
              @click="deletedFn(row)"
            >
              {{ translate('删除') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="total > 0" class="pagination">
        <el-pagination
          background
          :current-page="pageNo"
          :layout="layout"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      :title="translate('门店详情')"
      width="800px"
      @close="closeFn"
    >
      <el-form ref="formRef" label-width="120px" :model="form" :rules="rules">
        <detail :branchdetail="form" :from="submitType" />
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">
          {{ translate('取消') }}
        </el-button>
        <el-button type="primary" @click="submit">
          {{ translate('确定') }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getBranchList,
    branchedit,
    Base_BranchDown,
    Base_BranchExport,
  } from '@/api/branch'
  import { MenuAuth } from '~/src/utils/permission'
  import detail from './components/detail'
  import { parseTime } from '@/utils'
  import { baseURL } from '@/config'
  import { useUserStore } from '@/store/modules/user'
  import { translate } from '@/i18n'
  const { token } = useUserStore()
  export default defineComponent({
    name: 'Branch',
    components: { detail },
    data() {
      return {
        tableData: [],
        searchInfo: '',
        total: 0,
        pageNo: 1,
        pageSize: 20,
        layout: 'total, sizes, prev, pager, next, jumper',
        dialogVisible: false,
        submitType: 'add',
        timestamp: new Date().getTime(),
        action: '',
        headers: {},
        translate: translate,
        form: {
          BranchNo: '',
          BranchName: '',
          BranchType: 0,
          BranchTel: '',
          BranchAddress: '',
          BranchDescription: '',
          LogoURL: '',
          Mac: '',
          ContractName: '',
          ContractPhone: '',
          ContractEmail: '',
          BranchStatus: 0,
          SSValidity: '',
          Remark: '',
          Enabled: '',
        },
        rules: {
          BranchNo: [
            {
              required: true,
              trigger: 'blur',
              message: translate('请输入门店编号'),
            },
          ],
          BranchName: [
            {
              required: true,
              trigger: 'blur',
              message: translate('请输入门店名称'),
            },
          ],
        },
      }
    },
    created() {
      this.MenuAuths = MenuAuth
      this.getList()
    },
    methods: {
      async getList() {
        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          tableName: '',
          sort: '',
          order: '',
          wheres: JSON.stringify([
            { name: 'BranchName', value: this.searchInfo, displayType: 'like' },
          ]),
          export: false,
          value: '',
        }
        const data = await getBranchList(params)
        this.tableData = data.data.rows
        this.total = data.data.total
        console.log(this.tableData)
      },
      deletedFn(row) {
        this.$confirm(translate('确认删除该门店吗?'), translate('提示'), {
          confirmButtonText: translate('确定'),
          cancelButtonText: translate('取消'),
          type: 'warning',
        })
          .then(() => {
            this.deleted(row)
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: translate('已取消删除'),
            })
          })
      },
      async deleted(row) {
        const params = {
          branchid: row.BranchId,
        }
        const data = await delbranch(params)
        if (data.code == '200') {
          this.$message({
            message: translate('删除成功'),
            type: 'success',
          })
          await this.getList()
        }
      },
      //分页条数切换
      handleSizeChange(val) {
        this.pageSize = val
        this.getList()
      },
      //分页切换
      handleCurrentChange(val) {
        this.pageNo = val
        this.getList()
      },
      async addFn() {
        this.submitType = 'add'
        this.form = {
          BranchNo: '',
          BranchName: '',
          BranchType: 0,
          BranchTel: '',
          BranchAddress: '',
          BranchDescription: '',
          LogoURL: '',
          Mac: '',
          ContractName: '',
          ContractPhone: '',
          ContractEmail: '',
          BranchStatus: 1,
          SSValidity: '',
          Remark: '',
          Enabled: '',
        }
        this.dialogVisible = true
      },
      submit() {
        console.log(this.$refs)
        this.$refs['formRef'].validate(async (valid) => {
          if (valid) {
            console.log(valid)
            this.updataSaveList()
          }
        })
      },
      closeFn() {
        this.dialogVisible = false
      },
      async detailFn(row) {
        this.form = row
        this.submitType = 'edit'
        this.dialogVisible = true
        console.log(this.form)
      },

      async updataSaveList() {
        const params = this.form
        const data = await branchedit(params)
        if (data.code == '200') {
          this.getList()
          this.$message({
            message: translate('保存成功'),
            type: 'success',
          })
          this.dialogVisible = false
        }
      },
      // 下载物资表
      async download() {
        const data = await Base_BranchDown()
        if (data) {
          console.log(data)
          const blob = new Blob([data])
          const url = URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.download = `门店表.xlsx`
          link.href = url
          link.click()
        }
      },
      // 导出
      async exportFn() {
        this.listLoading = true
        const queryForm = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          tableName: '',
          sort: '',
          order: '',
          wheres: JSON.stringify([
            { name: 'BranchName', value: this.searchInfo, displayType: 'like' },
          ]),
          export: false,
          value: '',
        }
        const data = await Base_BranchExport(queryForm)
        const time = parseTime(new Date().getTime(), '{y}{m}{d}{h}{i}{s}')
        const blob = new Blob([data])
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.download = `门店表${time}.xlsx`
        link.href = url
        link.click()
        this.listLoading = false
      },
      handleError() {},
      beforeUpload() {},
      async uploadFn() {
        this.headers = this.headers = {
          Authorization: `Bearer ${token}`,
        }
        this.action = `${baseURL}/Base_Branch/Import`
      },
      async handleSuccess(data) {
        console.log(data)
        if (data.code === '200') {
          this.$message({
            message: translate('导入成功'),
            type: 'success',
          })
          this.getList()
        } else {
          this.$message({
            message: data.message,
            type: 'error',
          })
        }
      },
    },
  })
</script>
<style lang="scss" scoped>
  .flowpath-container {
    .color_494949 {
      color: #494949;
    }
    .w164 {
      width: 164px;
    }
    .mb20 {
      margin-bottom: 20px;
    }
    .mr10 {
      margin-right: 10px;
    }
    .img-container {
      display: flex;
      // justify-content: center;

      .img {
        width: 100px;
      }
    }
  }
  ::v-deep .el-form {
    display: flex;
    flex-flow: wrap;
    justify-content: left;
  }
  ::v-deep .el-form .el-input {
    width: 234px !important;
  }
  ::v-deep .el-form-item {
    width: 380px;
  }
  .inline-block {
    display: inline-block;
    margin: 0 10px;
    vertical-align: middle;
  }
  .add {
      margin-bottom: 10px;
      text-align: left;
    }
</style>
